package com.fingard.dsp.bank.directbank.hsbc02;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;

import java.util.Calendar;
import java.util.Date;

/**
 * 汇丰银行api明细查询
 * @date 20200426
 */
public class HSBC02Transaction extends HSBC02Base implements ITransaction {

    /**
     * 汇丰银行api历史明细查询
     * @param p_req7516
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        String tmpRespCode = "";
        String tmpRespInfo ="";
        try {
            //起始日期
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            //结束日期
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            while(tmpIntFrom<=tmpIntTo){
                //获取起始时间
                int intFromStep = tmpIntFrom;
                //起始时间+1
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                //重新设置起始时间
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                //查询明细数据
                String qryDate=Format.Date10Format.format(Format.Date8Format.parse(intFromStep+""));
                String[] decryptRsp=qryTransactionJson(p_req7516.actNum,qryDate);
                //处理响应
                if(decryptRsp[0].length()==0){
                    JSONObject balanceBodyJson=JSONObject.parseObject(decryptRsp[1]);
                    if(balanceBodyJson==null) {
                        tmpRespCode = "0";
                        tmpRespInfo = "Data is empty.";
                        continue;
                    }
                    JSONObject transactionsJson=balanceBodyJson.getJSONObject("transactions");
                    if(transactionsJson==null) {
                        tmpRespCode = "0";
                        tmpRespInfo = "Data is empty.";
                        continue;
                    }
                    String actNum=transactionsJson.getString("requestorAccountId");
                    if(!actNum.equals(p_req7516.actNum)){
                        tmpRespCode = "-1";
                        tmpRespInfo = "Query failed.";
                        continue;
                    }
                    //条数
                    String count=transactionsJson.getString("statementCount");
                    if(StringHelper.isNullOrEmpty(count) || Integer.parseInt(count)==0) {
                        tmpRespCode = "0";
                        tmpRespInfo = "No transactions found.";
                        continue;
                    }
                    JSONArray transationArray=transactionsJson.getJSONArray("transaction");
                    if(transationArray==null || transationArray.size()==0) {
                        tmpRespCode = "0";
                        tmpRespInfo = "No transactions found.";
                        continue;
                    }
                    //处理数据
                    for(int i=0;i<transationArray.size();i++){
                        JSONObject transationJson=transationArray.getJSONObject(i);
                        if(transactionsJson==null){
                            tmpRespCode = "0";
                            tmpRespInfo = "No transactions found.";
                            continue;
                        }
                        JSONObject items=transationJson.getJSONObject("items");
                        if(items==null){
                            tmpRespCode = "0";
                            tmpRespInfo = "No transactions found.";
                            continue;
                        }
                        JSONObject transactionAmount=items.getJSONObject("transactionAmount");
                        if(transactionAmount==null){
                            tmpRespCode = "0";
                            tmpRespInfo = "No transactions found.";
                            continue;
                        }
                        RetAtsTransDetail detail = new RetAtsTransDetail();
                        /**银行账号，本方*/
                        detail.actNum=actNum;
                        /**借贷标记*/
                        String cdFlag=items.getString("creditDebitIndicator");
                        /**交易日期，格式yyyy-MM-dd*/
                        detail.tranDate=items.getString("bookingDateTime");
                        /**交易时间，格式yyyy-MM-dd HH:mm:ss*/
                        detail.tranTime=detail.tranDate+" 00:00:00";
                        /**起息日，格式yyyy-MM-dd，银行没有返回就用tranDate交易日期*/
                        detail.valueDate=items.getString("valueDateTime");
                        /**备注*/
                        detail.comment=items.getString("transactionInformation");
                        /**币种，直联币种，人民币为1*/
                        detail.cur=convertCurToATS(transactionAmount.getString("currency"));
                        String tranAmt=transactionAmount.getString("amount");
                        if(tranAmt.startsWith("-")){
                            if("D".equals(cdFlag)){
                                detail.cdFlag="2";
                            }else if("C".equals(cdFlag)){
                                detail.cdFlag="1";
                            }
                            detail.tranAmt=tranAmt.substring(1);
                        }else {
                            if("D".equals(cdFlag)){
                                detail.cdFlag="1";
                            }else if("C".equals(cdFlag)){
                                detail.cdFlag="2";
                            }
                            detail.tranAmt=tranAmt;
                        }
                        /**支付流水号*/
                        detail.askNumber=items.getString("statementReference");
                        /**银行流水号（交易，支付提交时银行返回的流水号）*/
                        detail.bnkSeqNo=items.getString("transactionReference");
                        retAts.writeRetDetail(detail);
                    }
                }else if(decryptRsp[0].equals("RJCT") && decryptRsp[1].contains("No transactions found")){
                    tmpRespCode = "0";
                    tmpRespInfo = decryptRsp[1];
                }else {
                    tmpRespCode = "-1";
                    tmpRespInfo = decryptRsp[1];
                }
            }
        }catch (Exception ex) {
            tmpRespCode = "-1";
            tmpRespInfo = "Query exception："+ex.getMessage();
            WriteBankLogLn(ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        }else if(retAts.getWrittenRdCount() == 0) {
            retAts.writeRespInfo("No transactions found.");
            retAts.writeRespCode("0");
        }
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 汇丰银行api今日明细查询
     * @param p_req7515
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return 	d_7516_HisTrans(tmpReq7516);
    }
}
